package com.xiaoqiudong.controller;


import com.xiaoqiudong.mapper.UserInfoMapper;
import com.xiaoqiudong.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-08-15
 * Time:9:28
 */
@RestController
public class UserInfoController {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password ,HttpServletRequest request){
        //根据username查询数据
        User user = userInfoMapper.selectByName(username);
        System.out.println("[login] username ="+username);
        if (user == null || !password.equals(user.getPassword())){
            //登录失败
            System.out.println("登陆失败");
            return new User();
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("user",user);
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        try{
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userInfoMapper.insert(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e){
            User user = new User();
            return user;
        }
    }

    @GetMapping("/userinfo")
    @ResponseBody
    public Object getUserinfo(HttpServletRequest request){
        try {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            //拿着user对象 去数据库中找最新的数据
            User newUser = userInfoMapper.selectByName(user.getUsername());
            return newUser;
        }catch (NullPointerException e){
            return new User();
        }
    }
}
